package com.example.sparkmanager.task;

import com.example.sparkmanager.model.JobStatus;
import com.example.sparkmanager.model.SparkJob;
import com.example.sparkmanager.repository.SparkJobRepository;
import com.example.sparkmanager.service.SparkJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ScheduledJobTask implements Job {
    @Autowired
    private SparkJobService jobService;

    @Autowired
    private SparkJobRepository jobRepository;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Long jobId = context.getJobDetail().getJobDataMap().getLong("jobId");
        SparkJob job = jobRepository.findById(jobId)
                .orElseThrow(() -> new JobExecutionException("Job not found with id: " + jobId));

        if (job.getStatus() == JobStatus.SCHEDULED || job.getStatus() == JobStatus.FAILED) {
            jobService.triggerJob(jobId);
        }
    }
}